
import datetime
from datetime import datetime, timedelta
import json
from decimal import Decimal
from typing import List

import requests
from pymongo import MongoClient

from apps.zhcxkj_center_product.prod.views.get_sku_goor_num_all import Inventory
from common.setting import ensure_path_sep
from utils.mysqlUtils.db_pool import Database
import os
import threading
import time
from common.setting import ensure_path_sep
from utils.logging_tool.log_control import LogHandler
from utils.mysqlUtils.db_pool import Database
from utils.mysqlUtils.mongodb_utils import MongoDBLink



'''
一、获取 策略执行数据
    1. 传入 策略strategy_id ,通过 数据库 关联查询，商品类型 business_type(pop 或 半托), 渠道类型sku_type ,   t_strategy_rule_aliexpress：filter_val 平台过滤模板,商品过滤模板
    SELECT id,business_type,sku_type  
    FROM t_strategy_aliexpress
    WHERE id = 4 
    
    SELECT t_strategy_aliexpress.id,t_strategy_aliexpress.business_type,t_strategy_rule_aliexpress.filter_val
    FROM t_strategy_aliexpress
    RIGHT JOIN t_strategy_rule_aliexpress ON t_strategy_aliexpress.id = t_strategy_rule_aliexpress.strategy_id
    WHERE t_strategy_aliexpress.id = 4 
    
    select rule_code,filter_val from t_strategy_rule_aliexpress where strategy_id = %s
    2. 进入主流程 查询 动态库存变化表筛选的全部sku 
    3. 判断是否全部渠道,非全部渠道 过滤 渠道id
    4. 传入 模板id 调用封装的 商品过滤模板 
    5. 判断是否有 平台过滤, 封装平台过滤接口,传入 模板id 并调用 过滤得到最终 sku
二、获取 商品可用库存的 
三、判断策略 命中逻辑
'''


class ReplenishFilter:
    zhcxkj_center_replenish_db = Database(ensure_path_sep("\\config\\aliexpress_auto_replenish_config.yaml"),
                                                   "test_aliexpress_database")
    # t_sku_strategy_relation_aliexpress = MongoDBLink(
    #     uri='mongodb://admin:Zhcx?2021@10.158.158.29:27017/?authSource=admin',
    #     dbname='test_zhcxkj_java_center', coll_name='t_sku_strategy_relation')
    client = MongoClient('mongodb://admin:Zhcx?2021@10.158.158.29:27017/?authSource=admin')
    db = client['test_zhcxkj_java_center']
    collection = db['t_sku_strategy_relation']

    def __init__(self,strategy_id):
        self.strategy_id = strategy_id
        #  根据策略id查询策略条件
        get_strategy_details = f"""
        SELECT 
            a.status, -- '模板状态（1-启用、0-禁用）'
            a.strategy_type,  -- '策略类型（1创建促销 2修改促销 3删除促销 4下架 5调价 6刊登 7否定 8发货天数 9.自动补货）',
            a.business_type, -- '商品类型（速卖通：0-POP商品 2-全托管商品 ）',
            b.rule_code, -- '规则类型（规则类型编码，依据编码来选用处理器）',
            b.execute_type, -- 规则执行类型
            b.filter_val, -- 规则值
            b.filter_min_val, -- 最小值
            b.filter_max_val, -- 最大值
            b.filter_express -- 规则表达式
        FROM test_zhcxkj_center_strategy_comprehensive.t_replenishment_strategy_aliexpress a
        LEFT JOIN test_zhcxkj_center_strategy_comprehensive.t_replenishment_strategy_rule_aliexpress b on a.id=b.strategy_id
        WHERE a.id= {self.strategy_id}
        and a.strategy_type=9
        """
        strategy_conditions = self.zhcxkj_center_replenish_db.fetch_all_tuple(get_strategy_details)
        if not len(strategy_conditions):
            raise Exception("未查询到策略")
        if not strategy_conditions[0][0]:
            raise Exception("策略未启用")
        # 查询策略下渠道 source_id 以及 指定产品 sku_list
        get_source_id = f"""
        SELECT 
            a.sku_type, -- 'product_id：指定商品id，source_sku：指定渠道sku， sys_sku：指定系统sku'
            b.rule_code, -- '规则类型（规则类型编码，依据编码来选用处理器）',
            b.import_val -- '导入的值'
        FROM test_zhcxkj_center_strategy_comprehensive.t_replenishment_strategy_aliexpress a
        LEFT JOIN test_zhcxkj_center_strategy_comprehensive.t_replenishment_strategy_import_filter_aliexpress b on 
        a.id=b.import_id WHERE a.id= {self.strategy_id}
        """
        sql_list = self.zhcxkj_center_replenish_db.fetch_all_tuple(get_source_id)
        self.source_id_list = [] # 初始化一个列表来存储 渠道id
        self.product_id_list = []  # 初始化一个列表来存储 product_id
        if not len(sql_list):
            raise Exception("未查询到策略或为全部渠道")
        # sku_type  为空时，表示 指定渠道
        elif not sql_list[0][0]:
            for row in sql_list:
                self.source_id_list.append(row[2])
        else:
            for row in sql_list:
                self.product_id_list.append(row[2])
    def get_sku_list_and_stocks(self):


        get_sku_sql = f"""
        SELECT 
            a.sku,
            a.stock,
            b.rule_code, 
            b.import_val 
        FROM test_zhcxkj_center_warehouse.t_product_dynamic_inventory a
        LEFT JOIN test_zhcxkj_center_listing_comprehensive.t_replenishment_strategy_import_filter_aliexpress b on 
        a.id=b.import_id WHERE 'stock_update_time' >=  %s AND 'stock_update_time' < %s"
        """

    def filter_sku_list(self):
        get_filter_val_sql = f"""
        SELECT 
            rule_code, -- '规则类型（规则类型编码，依据编码来选用处理器）',
            filter_val -- '导入的值'
        FROM test_zhcxkj_center_strategy_comprehensive.t_replenishment_strategy_rule_aliexpress  WHERE strategy_id = {self.strategy_id}
        """

        filter_val_list = self.zhcxkj_center_replenish_db.fetch_all_tuple(get_filter_val_sql)
        # print(filter_val_list)
        filter_var = []
        for i in range(0,len(filter_val_list)):
            if 'product_filter' in filter_val_list[i]:
                filter_var.append(filter_val_list[i][1])
            if 'listing_template_filter' in filter_val_list[i]:
                filter_var.append(filter_val_list[i][1])
        print(filter_var)

        if not self.product_id_list:
            designated_products = self.product_id_list
            return designated_products


if __name__ == '__main__':
    test = ReplenishFilter(42)
    test.filter_sku_list()